package com.example.demo.controller;

import com.example.demo.common.Face;
import com.example.demo.common.Face_Rec;
import com.example.demo.common.Result;
import com.example.demo.entity.Attendance;
import com.example.demo.entity.Teacher;
import com.example.demo.mapper.AttendanceMapper;
import com.example.demo.mapper.TeacherMapper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.sql.Time;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author lai
 * @data 2021/11/16
 * @apiNote
 */
@RestController
@RequestMapping("/ter")
public class TeacherController {

    @Resource
    TeacherMapper teacherMapper;

    @Resource
    AttendanceMapper attendanceMapper;

    /**
     * 新增教师用户
     *
     * */
    @PostMapping
    public Result<?> save(@RequestBody Teacher teacher){
        Result result;
        try {
            teacherMapper.insert(teacher);
            result = Result.success(teacher.getId());
        }catch (Exception e){
            result = Result.fail();
            System.out.println(e);
        }
        return result;
    }

    /**
     * 更新教师信息
     *
     * */
    @PutMapping
    public Result<?> updata(@RequestBody Teacher teacher){
        Teacher test = new Teacher();
        test.setId(teacher.getId());
        test = teacher;
        teacherMapper.updateById(test);
        return Result.success();
    }

    /**
     * 查询全部教师数据
     *
     * */
    @GetMapping
    public Result<?> findAll(){
        List<Teacher> res = teacherMapper.selectList(null);
        return Result.success(res);
    }

    /**
     * 判断是否已有用户
     *
     *
     * @return*/
    @GetMapping("/findSame/{name}"+"&"+"{password}")
    public Result<?> findSame(@PathVariable String name, @PathVariable String password){
        Result result = null;
        List<Teacher> teachers = teacherMapper.selectList(null);
        for (int i = 0; i < teachers.size(); i++){
            if (name.equals(teachers.get(i).getName()) && password.equals(teachers.get(i).getPassword())) {
                result = Result.success(teachers.get(i));
                break;
            }
            else if (i == teachers.size()-1){
                result = Result.fail();
            }
        }
        return result;
    }

    /**
     * 根据id查询教师信息
     *
     * */
    @GetMapping("/{id}")
    public Result<?> find(@PathVariable Integer id){
        Teacher res = teacherMapper.selectById(id);
        return Result.success(res);
    }

    /**
     * 根据id删除教师
     *
     * */
    @DeleteMapping("/{id}")
    public Result<?> delte(@PathVariable Integer id){
        teacherMapper.deleteById(id);
        return Result.success();
    }

    /**
     * 头像上传
     *
     * id：更改头像的用户的id
     * portrait：头像地址
     * */
    @PostMapping("/"+"{id}"+"&"+"{portrait}")
    public void insertPortrait(@PathVariable Integer id,@PathVariable String portrait){
        portrait = portrait.replaceAll("，","/").replace("。","http://localhost:9090");
        Teacher teacher = new Teacher();
        teacher.setId(id);
        teacher.setPortrait(portrait);
        teacherMapper.updateById(teacher);
    }

    // 调用base64解析类

    Face face = new Face();

    // 调用人脸识别类

    Face_Rec face_rec = new Face_Rec();

    //设置时间格式

    SimpleDateFormat time = new SimpleDateFormat("HH:mm:ss");

    //设置日期格式

    SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd");

    // 录入当前时间
    
    String nowtime = time.format(new Date());

    /**
     * 上班打卡
     *
     * id：打卡人的id
     * base64：打卡人的人脸图像
     * */
    @PostMapping("/clockIn/{id}")
    public Result<?> clockIn(@PathVariable Integer id, @RequestBody String base64){
        Result result = new Result();
        try {
            if (!face_rec.face_res(face.getByt(base64)).equals("失败")){
                // 新建打卡对象
                Attendance attendance = new Attendance();
                // 录入打卡者id
                attendance.setTeacherId(id);
                // 录入当天日期
                attendance.setOndate(new java.sql.Date(System.currentTimeMillis()));
                // 将当前时间转换为sql.Date模式
                attendance.setOntime(new Time(System.currentTimeMillis()));
                // 判断打卡用户是否迟到
                if ((System.currentTimeMillis() > time.parse("08:30:00").getTime())){
                    attendance.setTerAction(2);
                }
                // 将对象插入数据库
                attendanceMapper.insert(attendance);
                System.out.println("打卡成功！！");
                result = Result.success();
            }
            else {
                System.out.println("打卡失败！！");
                result = Result.fail();
            }
        }catch (Exception ignored){
            System.out.println("打卡失败");
            result = Result.fail();
            System.out.println(ignored);
        }
        return result;
    }

    /**
     * 下班打卡
     *
     * base64：打卡人人脸图像
     * aid：打卡人今日打卡的数据id
     * */
    @PutMapping("/clockOff/{teacherid}")
    public Result<?> clockOff( @RequestBody String base64, @PathVariable Integer teacherid){
        Result result = new Result();
        try {
            if (face_rec.face_res(face.getByt(base64)).equals("失败")){
                int action = attendanceMapper.selectAction(
                        teacherid,
                        new java.sql.Date(System.currentTimeMillis())
                );
                // 判断打卡用户是否早退
                if ((System.currentTimeMillis() > time.parse("18:30:00").getTime())){
                    action += 1;
                }
                System.out.println(action);
                // 将数据更新入库
                attendanceMapper.updataByDate(
                        new Time(System.currentTimeMillis()),
                        action,
                        teacherid,
                        new java.sql.Date(System.currentTimeMillis())
                );

                result = Result.success();
                System.out.println("打卡成功");
            }else {
                System.out.println("打卡失败");
                result = Result.fail();
            }
        } catch (Exception ignored){
            System.out.println("打卡失败");
            result = Result.fail();
            System.out.println(ignored);
        }
        return result;
    }
}
